layui.use(['table', 'admin', 'ax','laydate','element'], function () {
    var $ = layui.$;
    var table = layui.table;
    var $ax = layui.ax;
    var admin = layui.admin;
    var laydate = layui.laydate;
	var element = layui.element;
	
	//tab切换
	element.on('tab(doTabBrief)',function(data){
		console.log(data.index)
	})

    laydate.render({
    	elem:'#hdTime'
    	, type:'month'
    	, value:getLastMonth()
    });

    laydate.render({
    	elem:'#startDate2'
    	, type:'month'
    	, value:getLastMonth()
    });
    
    function getLastMonth() {
	    var year,lastMonth;
	    var date = new Date();
	    var nowYear = date.getFullYear();   //当前年：四位数字
	    var nowMonth = date.getMonth();     //当前月：0-11
	    if (nowMonth == 0) {   //如果是0，则说明是1月份，上一个月就是去年的12月
	        year = nowYear - 1;
	        lastMonth = 12;
	    }else { //不是1月份，年份为当前年，月份本来是要减1的，但是由于`getMonth()`的月份本身就是少了1的，所以月份不用变。
	        year = nowYear;
	        lastMonth = nowMonth;
	    }
	    lastMonth = lastMonth < 10 ? ('0' + lastMonth) : lastMonth;   //月份格式化：月份小于10则追加个0
	    let lastYearMonth = year + '-' + lastMonth;
	    return lastYearMonth;
	}

    /**
     * 收入导入
     */
    var FinancialIncomeMatching = {
        tableId: "financialIncomeMatchingTable"
    };

    /**
     * 匹配
     */
    var TransportDispatch = {
        tableId: "transportDispatchTable"
    };

    /**
     * 初始化表格的列
     */
    FinancialIncomeMatching.initColumn = function () {
        return [[
            {type: 'checkbox'},
            {field: 'id', hide: true, title: '主键'},
            {field: 'operateName', sort: true, title: '归属项目'},
            {field: 'state', sort: true, title: '匹配状态',
            	templet: function(d){
            		var str = "";
            		if (d.state == '已匹配'){
                    	str += '<span style="color:#19be6b;font-weight: bold;">' + d.state + '</span>'
					} else {
                    	str += '<span style="font-weight: bold;">' + d.state + '</span>'
					}
            		return str
            	}
			},
            {field: 'customerOrder', sort: true, title: '客户单号', totalRowText: '合计：'},
            {field: 'v1', sort: true, title: '体积', totalRow: true},
            {field: 'freightMoney', sort: true, title: '运费', totalRow: true},
            {field: 'jsMonth', sort: true, title: '结算月份'},
            {field: 'hdTime', sort: true, title: '回单录入日期'},
            {field: 'createUserName', sort: true, title: '创建人'},
            {field: 'createTime', sort: true, title: '创建时间'},
        ]];
    };

    /**
     * 初始化表格的列
     */
    TransportDispatch.initColumn = function () {
        return [[
            {type: 'checkbox'},
            {field: 'id', hide: true, title: '主键id'},
            {field: 'operateName', sort: true, title: '归属项目'},
            {field: 'dispatchNumber', sort: true, title: '运输单号'},
            {field: 'tstate', sort: true, title: '运输状态', style:'color:#19be6b;font-weight: 600;'},
            {field: 'startDate', sort: true, title: '发车日期', style:'font-weight: 600;'},
            {field: 'jsMonth', sort: true, title: '结算月份', style:'font-weight: 600;'},
            {field: 'carrierName', sort: true, title: '承运商', style:'font-weight: 600;'},
            {field: 'lineName', sort: true, title: '线路', style:'font-weight: 600;'},
            {field: 'transportNumber', sort: true, title: '系统单号', style:'font-weight: 600;'},
            {field: 'customerOrder', sort: true, title: '客户单号', style:'font-weight: 600;'},
            {field: 'incomeState', sort: true, title: '是否匹配', style:'font-weight: 600;',
            	templet: function(d){
            		var str = "";
            		if (d.incomeState == '已匹配'){
                    	str += '<span style="color:#19be6b;font-weight: bold;">' + d.incomeState + '</span>'
					} else {
                    	str += '<span style="font-weight: bold;">' + d.incomeState + '</span>'
					}
            		return str
            	}
			},
            {field: 'freightMoney', sort: true, title: '运费'},
            {field: 'hdTime', sort: true, title: '回单录入日期'}
        ]];
    };

    /**
     * 点击查询按钮
     */
    FinancialIncomeMatching.search = function () {
        var queryData = {};
        queryData['condition'] = $("#condition").val();
        queryData['operateId'] = $("#operateId").val();
        queryData['hdTime'] = $("#hdTime").val();
        queryData['state'] = $("#state").val();
        table.reload(FinancialIncomeMatching.tableId, {
            where: queryData, page: {curr: 1},
             done:function () {
            }
        });
    };

    /**
     * 点击查询按钮
     */
    TransportDispatch.search = function () {
        var queryData = {};
        queryData['condition'] = $("#condition2").val();
        queryData['operateId'] = $("#operateId2").val();
        queryData['startDate'] = $("#startDate2").val();
        queryData['carrierId'] = $("#carrierId2").val();
        queryData['incomeState'] = $("#incomeState2").val();
        table.reload(TransportDispatch.tableId, {
            where: queryData, page: {curr: 1},
             done:function () {
            }
        });
    };
    
    // 导入
    $('#btnExpimport').click(function () {
        layer.open({
            type: 2,
            title: '收入匹配导入',
            area: ['1000px', '750px'],
            anim: 5,
            content: Feng.ctxPath + '/financialIncomeMatching/toimportExcel',
            end: function () {
                table.reload(FinancialIncomeMatching.tableId);
            }
        });
    });
    
    // 匹配
    $('#pipei').click(function () {
    	var operateId = $("#operateId").val();
    	if (operateId==null||operateId=='') {
    		layer.msg('请选择项目');
			return
		}
    	var hdTime = $("#hdTime").val();
    	if (hdTime==null||hdTime=='') {
    		layer.msg('请选择月份');
			return
		}
        layer.confirm('确定匹配发运明细吗？', function(index){
        	layer.close(index);
        	var msg;
            $.ajax({
            	url:Feng.ctxPath + "/financialIncomeMatching/pipei?operateId="+operateId+"&hdTime="+hdTime,
				data:{},
            	cache: false,
            	dataType:"json",
            	beforeSend:function(){
            		msg = layer.msg('提交中。。。请耐心等待', {
            			  icon: 16,
            			  shade: [0.2,'#000'], //0.1透明度的白色背景
            			  time: false
            		});
            	},
            	success:function(data){
                	layer.close(msg); 
            		if (data.success) {
                    	Feng.success("提交成功!");
                		table.reload(FinancialIncomeMatching.tableId);
                		table.reload(TransportDispatch.tableId);
					} else {
	                    Feng.error("提交失败！"+data.message);
					}
            	},
            	error:function(data){
                	layer.close(msg); 
                    Feng.error("提交失败！" + data.responseJSON.message)
            	}
            })
        }); 
    });

    /**
     * 导出excel按钮
     */
    FinancialIncomeMatching.exportExcel = function () {
        var checkRows = table.checkStatus(FinancialIncomeMatching.tableId);
        if (checkRows.data.length === 0) {
            Feng.error("请选择要导出的数据");
        } else {
            table.exportFile(tableResult.config.id, checkRows.data, 'xls');
        }
    };

    /**
     * 导出excel按钮
     */
    TransportDispatch.exportExcel = function () {
        var checkRows = table.checkStatus(TransportDispatch.tableId);
        if (checkRows.data.length === 0) {
            Feng.error("请选择要导出的数据");
        } else {
            table.exportFile(tableResult2.config.id, checkRows.data, 'xls');
        }
    };

    // 渲染表格
    var tableResult = table.render({
        elem: '#' + FinancialIncomeMatching.tableId,
        url: Feng.ctxPath + '/financialIncomeMatching/list',
        page: true,
        limit: 60,
		limits:[60,120,240,360,480,1500,5000],
        height: "full-60",
        totalRow: true ,//开启合计行
        toolbar: '#toolbarfrom',
        cellMinWidth: 100,
        cols: FinancialIncomeMatching.initColumn()
    });

    // 渲染表格
    var tableResult2 = table.render({
        elem: '#' + TransportDispatch.tableId,
        url: Feng.ctxPath + '/financialIncomeMatching/pplist',
        page: true,
        limit: 60,
		limits:[60,120,240,360,480,1500,5000],
        height: "full-60",
        toolbar: '#toolbarfrom',
        cellMinWidth: 100,
        cols: TransportDispatch.initColumn()
    });

    // 搜索按钮点击事件
    $('#btnSearch').click(function () {
        FinancialIncomeMatching.search();
    });

    // 搜索按钮点击事件
    $('#btnSearch2').click(function () {
        TransportDispatch.search();
    });

    // 导出excel
    $('#btnExp').click(function () {
        FinancialIncomeMatching.exportExcel();
    });

    // 导出excel
    $('#btnExp2').click(function () {
        TransportDispatch.exportExcel();
    });

});
